"""
模拟键鼠操作，自动导出数据

@Author:czy(zhenyuan.chen@stu.xjtu.edu.cn)
@Date:2025/9/11
@Version:v1.1.0
"""
from pywinauto import Application
import pyautogui
import time
from datetime import datetime, timedelta
import logging
import os

# 时间段长度
TIME_DELTA = timedelta(hours=1)

# 所需通道
CHANNELS = [2, 3, 4, 5, 6]


# 设置日志
def setup_logging():
    # 日志目录
    log_dir = "logs"
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 日志文件
    log_filename = f"{log_dir}/data_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"

    # 配置日志
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(log_filename),
            logging.StreamHandler()  # 同时输出到控制台
        ]
    )
    return logging.getLogger(__name__)


logger = setup_logging()


def activate_target_window(window_title):
    try:
        # 获取目标窗口
        windows = pyautogui.getWindowsWithTitle(window_title)
        if not windows:
            logger.error(f"未找到标题为 '{window_title}' 的窗口")
            return False

        target_window = windows[0]
        # 窗口最大化
        if not target_window.isMaximized:
            target_window.maximize()
        return True
    except Exception as e:
        logger.error(f"激活窗口时发生错误: {str(e)}")
        return False


def main():
    # 获取时间
    end_time = datetime.now()
    start_time = end_time - TIME_DELTA

    if not activate_target_window("H960GC_V1.4.2.3"):
        logger.error("无法激活目标窗口，程序终止")
        return

    time.sleep(5)

    try:
        # 连接到目标应用
        logger.info("尝试连接到应用程序...")
        app = Application(backend="uia").connect(title="H960GC_V1.4.2.3")
        logger.info("应用程序连接成功")
    except Exception as e:
        logger.error(f"连接应用程序失败: {str(e)}")
        return

    try:
        # 连接窗口
        window = app.window(title="H960GC_V1.4.2.3")
        logger.info("窗口对象获取成功")
    except Exception as e:
        logger.error(f"获取窗口对象失败: {str(e)}")
        return

    # 输入开始时间
    try:
        start_time_combo = window.child_window(auto_id="dtStartDate")
        start_time_combo.type_keys(start_time.strftime("%Y-%m-%d-%H-%M-%S-"))
        logger.info("输入开始时间：" + start_time.strftime("%Y-%m-%d-%H-%M-%S"))
    except Exception as e:
        logger.error(f"输入开始时间失败: {str(e)}")
        return

    # 输入结束时间
    try:
        end_time_combo = window.child_window(auto_id="dtEndDate")
        end_time_combo.type_keys(end_time.strftime("%Y-%m-%d-%H-%M-%S-"))
        logger.info("输入结束时间：" + end_time.strftime("%Y-%m-%d-%H-%M-%S"))
    except Exception as e:
        logger.error(f"输入结束时间失败: {str(e)}")
        return

    # 获取读取数据按钮控件
    try:
        button = window.child_window(auto_id="btnReadData", control_type="Button")
        logger.info("找到读取数据按钮")
    except Exception as e:
        logger.error(f"找不到读取数据按钮: {str(e)}")
        return

    # 预加载所有通道复选框
    channel_checkboxes = {}
    for chan in CHANNELS:
        try:
            channel_checkboxes[chan] = window.child_window(auto_id=f"checkTD{chan}")
            logger.info(f"找到通道 {chan} 的复选框")
        except Exception as e:
            logger.error(f"找不到通道 {chan} 的复选框: {str(e)}")
            # 如果找不到某个通道的复选框，跳过该通道
            continue

    # 导出数据
    for channel_id in CHANNELS:
        if channel_id not in channel_checkboxes:
            logger.warning(f"跳过通道 {channel_id}，因为未找到其复选框")
            continue

        logger.info(f"开始处理通道 {channel_id}")

        try:
            # 勾选通道
            logger.info(f"勾选通道 {channel_id}")
            channel_checkboxes[channel_id].click()
        except Exception as e:
            logger.error(f"勾选通道 {channel_id} 失败: {str(e)}")
            continue

        try:
            # 点击读取数据按钮
            logger.info("点击读取数据按钮")
            button.click()
        except Exception as e:
            logger.error(f"点击读取数据按钮失败: {str(e)}")
            # 取消勾选当前通道
            try:
                channel_checkboxes[channel_id].click()
            except:
                pass
            continue

        time.sleep(120)

        # 关闭弹窗
        pyautogui.press('enter')

        try:
            # 取消勾选通道
            logger.info(f"取消勾选通道 {channel_id}")
            channel_checkboxes[channel_id].click()
        except Exception as e:
            logger.error(f"取消勾选通道 {channel_id} 失败: {str(e)}")

        logger.info(f"通道 {channel_id} 处理完成")



if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        logger.error(f"程序执行过程中发生未捕获的异常: {str(e)}")
        logger.exception("异常详细信息:")
